package com.md.application.assembler;

import com.google.common.collect.Lists;
import com.md.domain.model.bo.QueryRoleBo;
import com.md.domain.model.bo.RoleBo;
import com.md.domain.model.po.Role;
import com.md.domain.model.po.RoleApis;
import com.md.model.request.authentication.role.InsertRoleRequest;
import com.md.model.request.authentication.role.QueryRoleRequest;
import com.md.model.response.authentication.role.RoleDetailResponse;
import com.md.model.response.authentication.role.RoleResponse;
import com.md.model.response.system.DictionariesDetailsResponse;
import com.md.util.ClassUtils;
import com.md.value.constants.AuthenticationConstants;
import com.md.value.enums.AuthEnum;
import lombok.experimental.UtilityClass;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

/**
 * @author 刘骄阳
 * 2023-09-21 18:33
 */
@UtilityClass
public class RoleAssembler {

  public static RoleDetailResponse buildRoleDetailResponse(final Role role) {
    return ClassUtils.source2Target(role, RoleDetailResponse.class);
  }

  public static void buildInsertRoleRequest(final InsertRoleRequest request) {
    if (ObjectUtils.isEmpty(request.getParentId())) {
      request.setParentId(AuthenticationConstants.DEFAULT_ROLE_PARENT_ID);
    }
  }

  public static RoleBo buildInsertRoleBo(final String name, final Long parentId,
                                         final RoleDetailResponse roleDetailResponse) {
    RoleBo roleBo = new RoleBo();
    List<RoleApis> roleApisList = Lists.newArrayList();
    Role role = Role.builder().name(name).parentId(parentId).build();
    if (!ObjectUtils.isEmpty(roleDetailResponse)) {
      // 说明有父级
      roleDetailResponse.getApiList().forEach(apiResponse -> {
        if (AuthEnum.NEED != apiResponse.getAuth()) {
          return;
        }
        RoleApis roleApis = new RoleApis();
        roleApis.setApiId(apiResponse.getId());
        roleApis.setExtendsParentRole(true);
        roleApisList.add(roleApis);
      });
      role.setRootId(roleDetailResponse.getRootId());
    }
    roleBo.setRole(role);
    roleBo.setAddRoleApisList(roleApisList);
    return roleBo;
  }

  public static QueryRoleBo buildQueryRoleBo(final QueryRoleRequest request) {
    return ClassUtils.source2Target(request, QueryRoleBo.class);
  }

  public static List<RoleResponse> buildRoleResponse(final List<Role> records,
                                                     final DictionariesDetailsResponse dictionariesDetails,
                                                     final Map<Long, Integer> roleApiCount) {
    List<RoleResponse> list = Lists.newArrayList();
    records.forEach(role -> {
      RoleResponse response = ClassUtils.source2Target(role, RoleResponse.class);
      response.setCount(roleApiCount.getOrDefault(role.getId(), 0));
      response.setIsMasterRole(String.valueOf(role.getId()).equals(dictionariesDetails.getValue()));
      list.add(response);
    });
    return list;
  }
}
